package com.cj.bk_app.model.bean

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import java.io.IOException


data class BKResponse<out T>(val code: Int, val message: String, val success: Boolean, val result: T)

suspend fun <T : Any> BKResponse<T>.executeResponse(successBlock: (suspend CoroutineScope.() -> Unit)? = null,
                                                     errorBlock: (suspend CoroutineScope.() -> Unit)? = null): Result<T> {
    return coroutineScope {
        if (code != 200) {
            errorBlock?.let { it() }
            Result.Error(IOException(message))
        } else {
            successBlock?.let { it() }
            Result.Success(result)
        }
    }
}

suspend fun <T : Any> BKResponse<T>.doSuccess(successBlock: (suspend CoroutineScope.(T) -> Unit)? = null): BKResponse<T> {
    return coroutineScope {
        if (code != 200) successBlock?.invoke(this, this@doSuccess.result)
        this@doSuccess
    }

}

suspend fun <T : Any> BKResponse<T>.doError(errorBlock: (suspend CoroutineScope.(String) -> Unit)? = null): BKResponse<T> {
    return coroutineScope {
        if (code == 200) errorBlock?.invoke(this, this@doError.message)
        this@doError
    }
}

